<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>瀑布流</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .container {
            position: relative;
            margin-left: 15px;
        }

        .container>div {
            position: absolute;
            float: left;
            width: 200px;
            text-align: center;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
        <div class="item">5</div>
        <div class="item">6</div>
        <div class="item">7</div>
        <div class="item">8</div>
        <div class="item">9</div>
        <div class="item">10</div>
        <div class="item">11</div>
        <div class="item">12</div>
    </div>
    <script>

        window.onload = () => {
            setBoxPosition()
        }

        window.onresize = function(){
            setBoxPosition()
        }

        // 设置盒子布局的方法
        function setBoxPosition() {
            // 获取盒子数组
            let itemDom = document.querySelectorAll(".item")

            const colorList = ['aqua', 'aquamarine', 'blueviolet', 'brown', 'deepskyblue', 'khaki', 'red', 'thistle', 'orange', 'palevioletred', 'teal', 'crimson']

            // 间隙
            const gap = 20


            // 判断一行有多少列
            // 显示的列数 = 页面宽度/（盒子宽度 + 间隙）
            const column = Math.floor(screen.width / (200 + gap))

            // 保存每列高度的height
            let heightArr = []

            // 最小列高度的index
            let minIndex

            // 确定第一行
            for (let i = 0; i < itemDom.length; i++) {

                let boxHeight = Math.floor(Math.random() * 100 + 150)

                itemDom[i].style.height = boxHeight + 'px'
                itemDom[i].style.lineHeight = boxHeight + 'px'
                itemDom[i].style.background = colorList[i]

                if (i < column) {
                    itemDom[i].style.top = 0
                    itemDom[i].style.left = (200 + 20) * i + 'px'
                    heightArr.push(boxHeight)
                } else {
                    minIndex = sort(heightArr)
                    itemDom[i].style.left = itemDom[minIndex].offsetLeft + 'px'
                    itemDom[i].style.top = heightArr[sort(heightArr)] + 20 + 'px'
                    heightArr[minIndex] = heightArr[minIndex] + 20 + boxHeight

                }


            }
        }

        // 数组查询最低值
        function sort(arr) {
            let min = arr[0]
            let index = 0
            for (let i = 1; i < arr.length; i++) {
                if (min > arr[i]) {
                    min = arr[i]
                    index = i
                }
            }

            return index
        }

    </script>

    <body>

</html>